<template>
<view class="container">
  <view class="search_top" :style="'background:' + setting.platformSetting.topBgColor">
    <view class="search_input">
      <input class="search_input_text" :value="searchValue" confirm-type="search" @input="saveSearchValue" @confirm="getSearchProductName" placeholder-class="phcolor" :placeholder="(properties.tip_product_search?properties.tip_product_search:'保障源于专业，30分钟送达')"></input>
      <image @click.stop="getSearchProductName" class="search_input_icon" src="https://image1.sansancloud.com/xianhua/2019_4/2/14/30/34_688.jpg?x-oss-process=style/preview_120"></image>
    </view>
  </view>
  <view class="interval"></view>
  <view class="search_list">
    <view class="search_item" v-if="searchStorage.length!=0">
      <view class="search_item_top">
        <text class="search_item_top_title">历史</text>
        <text class="delete_value" @click.stop="clearSearchStorage">清空</text>
      </view>
      <view class="search_item_value_list">
        <view class="search_item_value_item" :data-value="item.name" @click.stop="saveSearchValue" v-for="(item, index) in searchStorage" :key="index">{{item.name}}</view>
      </view>
    </view>
    <view class="search_item" v-if="hotSearchList.length!=0">
      <view class="search_item_top">
        <text class="search_item_top_title">猜你想找</text>
        <text></text>
      </view>
      <view class="search_item_value_list">
        <view class="search_item_value_item" :data-value="item.tagName" @click.stop="saveSearchValue" v-for="(item, index) in hotSearchList" :key="index">{{item.tagName}}</view>
      </view>
    </view>
  </view>
  <!-- <view class='search_banner'>
    <image class='search_banner_img' src=''></image>
  </view> -->
</view>
</template>

<script>

export default {
  data() {
    return {
      setting: null,
      // setting   
      searchStorage: [],
      searchValue: "",
      hotSearchList: [],
      listPage: {
        page: 1,
        pageSize: 0,
        totalSize: 0,
        curpage: 1
      },
      assetsList: "",
      properties: ""
    };
  },

  components: {},
  props: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    that.initSetting();
    let searchStorage = wx.getStorageSync('searchData') || [];
    console.log("===searchStorage====", searchStorage);
    that.setData({
      searchStorage: searchStorage
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.listPage.page = 1;
    this.params.page = 1;
    this.getData(this.params, 2);
    wx.showNavigationBarLoading();
    wx.hideNavigationBarLoading(); //完成停止加载

    wx.stopPullDownRefresh(); //停止下拉刷新
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this;

    if (that.listPage.totalSize > that.listPage.curPage * that.listPage.pageSize) {
      that.listPage.page++;
      that.params.page++;
      this.getData(this.params);
    }
  },
  methods: {
    toIndex() {
      getApp().globalData.toIndex();
    },

    clearSearchStorage: function () {
      wx.removeStorageSync('searchData');
      this.setData({
        searchStorage: []
      });
    },

    /* 查找商品 */
    getSearchProductName: function (e) {
      console.log("===getSearchProductName===");
      let that = this;
      let searchData = that.searchStorage;
      console.log("===searchStorage-start==", searchData);

      if (searchData.length != 0) {
        console.log("历史有数据");
        let count = 0;

        for (let i = 0; i < searchData.length; i++) {
          if (searchData[i].name != that.searchValue && that.searchValue != "") {
            count++;
          }
        }

        if (count == searchData.length) {
          searchData.push({
            id: searchData.length,
            name: that.searchValue
          });
        }
      } else {
        console.log("历史没数据");

        if (that.searchValue != "") {
          searchData.push({
            id: searchData.length,
            name: that.searchValue
          });
        }
      }
      console.log("===searchStorage-end==", searchData);
      wx.setStorageSync('searchData', searchData); // let pages = getCurrentPages();//当前页面
      // let prevPage = pages[pages.length - 2];//上一页面
      // prevPage.setData({//直接给上移页面赋值
      //   searchValue: that.searchValue,
      // });
      // wx.navigateBack(
      //   { delta: 1, }
      // )
      that.tolinkUrl("material_library_detail.html?searchstr=" + that.searchValue);
    },
    saveSearchValue: function (e) {
      console.log("===saveSearchValue===", e);
      let that = this;

      if (e.detail.value || e.currentTarget.dataset.value) {
        that.searchValue = e.currentTarget.dataset.value ? e.currentTarget.dataset.value : e.detail.value.replace(/\s+/g, '');
      } else {
        that.searchValue = "";
      }
      if (e.currentTarget.dataset.value) {
        that.getSearchProductName();
      }
      console.log("that.searchValue", that.searchValue);
    },

    /* 获取数据 */
    getData: function (param, ifAdd) {
      //根据把param变成&a=1&b=2的模式
      if (!ifAdd) {
        ifAdd = 1;
      }

      var customIndex = getApp().globalData.AddClientUrl("/wx_find_space_assets.html", param); // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      var that = this;
      wx.request({
        url: customIndex.url,
        header: getApp().globalData.header,
        success: function (res) {
          wx.hideLoading();
          console.log(res.data);
          that.listPage.pageSize = res.data.relateObj.pageSize;
          that.listPage.curPage = res.data.relateObj.curPage;
          that.listPage.totalSize = res.data.relateObj.totalSize;
          let dataArr = that.assetsList;

          if (ifAdd == 2) {
            dataArr = [];
          }

          if (!res.data.relateObj.result || res.data.relateObj.result.length == 0) {
            that.setData({
              assetsList: null
            });
          } else {
            if (dataArr == null) {
              dataArr = [];
            }

            dataArr = dataArr.concat(res.data.relateObj.result);
            that.setData({
              assetsList: dataArr
            });
          }
        },
        fail: function (res) {
          console.log("fail");
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },

    /* 组件事件集合 */
    tolinkUrl: function (e) {
      let linkUrl = e.currentTarget ? e.currentTarget.dataset.link : e;
      getApp().globalData.linkEvent(linkUrl);
    },

    initSetting() {
      console.log("===setting===", getApp().globalData.setting, getApp().globalData.properties);
      let hotSearchList = getApp().globalData.setting.platformSetting.tagsMap["产品热搜"] || [];
      this.setData({
        setting: getApp().globalData.setting,
        hotSearchList: hotSearchList,
        properties: getApp().globalData.properties
      });
      wx.setNavigationBarColor({
        frontColor: getApp().globalData.setting.platformSetting.topColor.toLowerCase(),
        backgroundColor: getApp().globalData.setting.platformSetting.topBgColor
      });
    },

    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>